import sys

from PyQt5 import QtCore
from PyQt5.QtCore import pyqtSlot, Qt, QItemSelectionModel, QModelIndex, QFile, QIODevice,QTimer
from PyQt5.QtGui import QPixmap,QIcon
from PyQt5.QtSql import QSqlDatabase, QSqlTableModel
from PyQt5.QtWidgets import QApplication, QDialog,QMainWindow,QLineEdit, QFileDialog, QAbstractItemView, QMessageBox, QDataWidgetMapper

from myDelegates import QmyComboBoxDelegate
from ui_MainWindow import Ui_MainWindow
from ui_logoin import Ui_logoin


class Qmylogoin(QDialog):
    # logoinSignal = QtCore.pyqtSignal(int)
    def __init__(self,parent = None):
        super(Qmylogoin, self).__init__(parent)
        self.ui = Ui_logoin()
        self.ui.setupUi(self)
        self.user_message = [self.ui.lineEdit_userName,self.ui.lineEdit_password]
        self.ui.lineEdit_userName.setPlaceholderText("用户名")
        self.ui.lineEdit_password.setPlaceholderText("密码")
        self.ui.lineEdit_password.setEchoMode(QLineEdit.Password)
        self.setWindowTitle("饰品管理系统登录界面")


class QmyMainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(QmyMainWindow, self).__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.setCentralWidget(self.ui.splitter)
        self.setWindowTitle("饰品管理系统_V0.1")
        self.setWindowIcon(QIcon("bitbug_favicon.ico"))
        # tableView属性设置
        self.ui.tableView.setSelectionBehavior(QAbstractItemView.SelectItems)
        self.ui.tableView.setSelectionMode(QAbstractItemView.SingleSelection)
        self.ui.tableView.setAlternatingRowColors(True)
        self.ui.tableView.verticalHeader().setDefaultSectionSize(22)
        self.ui.tableView.horizontalHeader().setDefaultSectionSize(100)

    # 选择数据库
    @pyqtSlot()
    def on_actOpenDB_triggered(self):
        dbFilename, flt = QFileDialog.getOpenFileName(self, "选择数据库文件", "", "SQL Lite数据库(*.db *.db3)")
        if dbFilename == "":
            return
        self.DB = QSqlDatabase.addDatabase("QSQLITE")
        self.DB.setDatabaseName(dbFilename)
        if self.DB.open():
            self.__openTable()
        else:
            QMessageBox.Warning(self, "错误", "打开数据库失败")

    def __getFieldNames(self):
        emptyRec = self.tabModel.record()
        self.fldNum = {}
        for i in range(emptyRec.count()):
            fieldName = emptyRec.fieldName(i)
            self.ui.comboFields.addItem(fieldName)
            self.fldNum.setdefault(fieldName)
            self.fldNum[fieldName] = i
        self.ui.comboFields.setEnabled(True)
        self.ui.radioButtonDescend.setEnabled(True)
        self.ui.radioButtonAscend.setEnabled(True)
        self.ui.radioButtonXl.setEnabled(True)
        self.ui.radioButtonSl.setEnabled(True)
        self.ui.radioButtonJz.setEnabled(True)
        self.ui.radioButtonEd.setEnabled(True)
        self.ui.radioButtonBoth.setEnabled(True)
        # print(self.fldNum)

    def __openTable(self):
        self.tabModel = QSqlTableModel(self,self.DB)
        self.tabModel.setTable("Ornament_list")
        self.tabModel.setSort(self.tabModel.fieldIndex("OrnamentNo"),Qt.AscendingOrder)
        self.tabModel.setEditStrategy(QSqlTableModel.OnManualSubmit)
        if not self.tabModel.select():
            QMessageBox.critical(self,"出错消息","打开数据表错误，出错信息\n"+self.tabModel.lastError().text())
            return
        self.__getFieldNames()
        # 设置字段显示名
        self.tabModel.setHeaderData(self.fldNum["OrnamentNo"],Qt.Horizontal,"饰品编号")
        self.tabModel.setHeaderData(self.fldNum["Name"],Qt.Horizontal,"饰品名称")
        self.tabModel.setHeaderData(self.fldNum["OrnamentType"],Qt.Horizontal,"饰品类别")
        self.tabModel.setHeaderData(self.fldNum["JinHuoDate_1"],Qt.Horizontal,"进货时间_1")
        self.tabModel.setHeaderData(self.fldNum["Materials"],Qt.Horizontal,"材料")
        self.tabModel.setHeaderData(self.fldNum["OrnamentPrice"],Qt.Horizontal,"饰品进价(￥)")
        self.tabModel.setHeaderData(self.fldNum["Demo"],Qt.Horizontal,"备注")
        self.tabModel.setHeaderData(self.fldNum["Photo"],Qt.Horizontal,"照片")
        # 创建界面组件与数据模型之间的数据映射
        self.mapper = QDataWidgetMapper()
        self.mapper.setModel(self.tabModel)
        self.mapper.setSubmitPolicy(QDataWidgetMapper.AutoSubmit)
        # 界面组件与tabModel的具体字段联系
        self.mapper.addMapping(self.ui.article_bh,self.fldNum["OrnamentNo"])
        self.mapper.addMapping(self.ui.article_name,self.fldNum["Name"])
        self.mapper.addMapping(self.ui.dbComboType,self.fldNum["OrnamentType"])
        self.mapper.addMapping(self.ui.dbInputDate,self.fldNum["JinHuoDate_1"])
        self.mapper.addMapping(self.ui.dbComboMaterial,self.fldNum["Materials"])
        self.mapper.addMapping(self.ui.spinBox_jj,self.fldNum["OrnamentPrice"])
        self.mapper.addMapping(self.ui.dbEditMemo,self.fldNum["Demo"])
        self.mapper.toFirst()

        self.selModel = QItemSelectionModel(self.tabModel)
        self.selModel.currentChanged.connect(self.do_currentChanged)
        self.selModel.currentRowChanged.connect(self.do_currentRowChanged)

        self.ui.tableView.setModel(self.tabModel)
        self.ui.tableView.setSelectionModel(self.selModel)
        # self.ui.tableView.setColumnHidden(self.fldNum["Demo"],True)
        self.ui.tableView.setColumnHidden(self.fldNum["Photo"],True)
        # 两个字段设置自定义代理组件
        strList = ("项链","手链","耳钉","戒指")
        self.__delegateSex = QmyComboBoxDelegate()
        self.__delegateSex.setItems(strList,False)
        # combobox选择模型
        self.ui.tableView.setItemDelegateForColumn(self.fldNum["OrnamentType"],self.__delegateSex)
        strList = ("纯银","铜","铜坠、通体钛钢","银针,主体合金","宝珠")
        self.__delegateDepart = QmyComboBoxDelegate()
        self.__delegateDepart.setItems(strList,True)
        self.ui.tableView.setItemDelegateForColumn(self.fldNum["Materials"],self.__delegateDepart)

        self.ui.actOpenDB.setEnabled(False)
        self.ui.actRecAppend.setEnabled(True)
        self.ui.actInsert.setEnabled(True)
        self.ui.actRecDelete.setEnabled(True)
        self.ui.groupBoxSort.setEnabled(True)
        self.ui.groupBoxFilter.setEnabled(True)

    def do_currentChanged(self,current,previous):
        self.ui.actSubmit.setEnabled(self.tabModel.isDirty())
        self.ui.actRevert.setEnabled(self.tabModel.isDirty())

    def do_currentRowChanged(self,current,previous):
        self.ui.actRecDelete.setEnabled(current.isValid())
        self.ui.actPhoto.setEnabled(current.isValid())
        self.ui.actPhotoClear.setEnabled(current.isValid())
        if not current.isValid():
            self.ui.label_3.clear()
            return
        self.mapper.setCurrentIndex(current.row())
        curRec = self.tabModel.record(current.row())
        if curRec.isNull("Photo"):
            self.ui.label_3.clear()
        else:
            data = curRec.value("Photo")
            pic = QPixmap()
            pic.loadFromData(data)
            W = self.ui.label_3.size().width()
            self.ui.label_3.setPixmap(pic.scaledToWidth(W))

    @pyqtSlot()
    def on_actRecAppend_triggered(self):
        self.tabModel.insertRow(self.tabModel.rowCount(), QModelIndex())
        curIndex = self.tabModel.index(self.tabModel.rowCount() - 1, 1)
        self.selModel.clearSelection()
        self.selModel.setCurrentIndex(curIndex, QItemSelectionModel.Select)
        currow = curIndex.row()
        self.tabModel.setData(self.tabModel.index(currow, self.fldNum["OrnamentNo"]), self.tabModel.rowCount()+1)
        self.tabModel.setData(self.tabModel.index(currow, self.fldNum["OrnamentType"]), "项链")

    @pyqtSlot()
    def on_actInsert_triggered(self):
        curIndex = self.ui.tableView.currentIndex()
        self.tabModel.insertRow(curIndex.row(), QModelIndex())
        self.selModel.clearSelection()
        self.selModel.setCurrentIndex(curIndex, QItemSelectionModel.Select)

    @pyqtSlot()
    def on_actRecDelete_triggered(self):
        curIndex = self.selModel.currentIndex()
        result = QMessageBox.question(self, "提示信息", "是否确认删除行", QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel,
                                      QMessageBox.No)
        if result == QMessageBox.Yes:
            self.tabModel.removeRow(curIndex.row())

    @pyqtSlot()
    def on_actSubmit_triggered(self):
        res = self.tabModel.submitAll()
        if not res:
            QMessageBox.information(self, "消息", "数据保存错误，出错消息\n" + self.tabModel.lastError().text())
        else:
            self.ui.actSubmit.setEnabled(True)
            self.ui.actRevert.setEnabled(True)

    @pyqtSlot()
    def on_actRevert_triggered(self):
        self.tabModel.revertAll()
        self.ui.actSubmit.setEnabled(False)
        self.ui.actRevert.setEnabled(False)

    @pyqtSlot()
    def on_actPhoto_triggered(self):
        filename, flt = QFileDialog.getOpenFileName(self, "选择图片文件", "", "图片(*.jpg *.png *.ico)")
        if not filename:
            return
        file = QFile(filename)
        file.open(QIODevice.ReadOnly)
        try:
            data = file.readAll()
        finally:
            file.close()
        curRecNo = self.selModel.currentIndex().row()
        curRec = self.tabModel.record(curRecNo)
        curRec.setValue("Photo", data)
        self.tabModel.setRecord(curRecNo, curRec)
        pic = QPixmap()
        pic.loadFromData(data)
        W = self.ui.label_3.width()
        self.ui.label_3.setPixmap(pic.scaledToWidth(W))

    @pyqtSlot()
    def on_actPhotoClear_triggered(self):
        curRecNo = self.selModel.currentIndex().row()
        curRec = self.tabModel.record(curRecNo)
        curRec.setNull("Photo")
        self.tabModel.setRecord(curRecNo, curRec)
        self.ui.label_3.clear()

    @pyqtSlot()
    def on_comboFields_currentIndexChanged(self, index):
        if self.ui.radioButtonAscend.isChecked():
            self.tabModel.setSort(index, Qt.AscendingOrder)
        else:
            self.tabModel.setSort(index, Qt.DescendingOrder)
        self.tabModel.select()

    @pyqtSlot()
    def on_radioButtonEd_clicked(self):
        self.tabModel.setFilter("OrnamentType='耳钉'")

    @pyqtSlot()
    def on_radioButtonJz_clicked(self):
        self.tabModel.setFilter("OrnamentType='戒指'")

    @pyqtSlot()
    def on_radioButtonSl_clicked(self):
        self.tabModel.setFilter("OrnamentType='手链'")

    @pyqtSlot()
    def on_radioButtonXl_clicked(self):
        self.tabModel.setFilter("OrnamentType='项链'")

    @pyqtSlot()
    def on_radioButtonBoth_clicked(self):
        self.tabModel.setFilter("")

    @pyqtSlot()
    def on_radioButtonAscend_clicked(self):
        self.tabModel.setSort(self.ui.comboFields.currentIndex(),Qt.AscendingOrder)
        self.tabModel.select()

    @pyqtSlot()
    def on_radioButtonDescend_clicked(self):
        self.tabModel.setSort(self.ui.comboFields.currentIndex(),Qt.DescendingOrder)
        self.tabModel.select()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    form = QmyMainWindow()
    logoin = Qmylogoin(form)
    result = False
    while logoin.exec():
        if logoin.ui.lineEdit_userName.text().lower()=="shijiaojiao" and logoin.ui.lineEdit_password.text() == "20230618":
            result = True
            break
        else:
            QMessageBox.question(logoin, "提示信息", "用户名或密码错误请重新输入", QMessageBox.Yes)
            logoin.ui.lineEdit_userName.clear()
            logoin.ui.lineEdit_password.clear()
    if result:
        form.show()
        sys.exit(app.exec())
    else:
        sys.exit()